package org.security.annotation.aop;

import lombok.SneakyThrows;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.pmw.tinylog.Logger;
import org.security.annotation.PreAuthorizer;
import org.security.annotation.able.AuthertizerAble;
import org.security.config.FreeProperties;
import org.security.config.web.AbstractFreeSecurityWebConfig;
import org.security.enums.CustomExceptionType;
import org.security.exception.CustomException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * @author jt
 * @version 1.0
 * @date 2024/6/25 15:29
 */
@Aspect
@Component
public class AuthorizerAspect {

    @Autowired
    private AuthertizerAble authertizerAble;

    @Autowired
    private FreeProperties properties;

    @Pointcut("@annotation(org.security.annotation.PreAuthorizer)")
    private void cutMethod(){}

    @Around("cutMethod()")
    @SneakyThrows
    public Object around(ProceedingJoinPoint joinPoint) {
        HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpServletResponse response=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        String token = request.getHeader(properties.getTokenKey());
        PreAuthorizer preAuthorizer = ((MethodSignature)joinPoint
                .getSignature())
                .getMethod()
                .getAnnotation(PreAuthorizer.class);
        String value = preAuthorizer.value();
        List<String> scopes = Arrays.asList(value.split(","));
        if(scopes.size()<1){
            Logger.info("无需授权");
            return false;
        }
        if(!haveAuthority(scopes,token)){
            CustomException.errorToResponse(response, HttpStatus.UNAUTHORIZED, CustomExceptionType.UNAUTHORIZED);
            return false;
        }
        else return joinPoint.proceed();
    }

    private boolean haveAuthority(List<String> scopes,String token) {

        //实现授权的实现逻辑
        return authertizerAble.haveAuthority(scopes,token);
    }
}
